/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.ungzip;

import cn.ac.iie.di.global.GlobalParas;
import java.util.ArrayList;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 *
 * @author lenovo-pc
 */
public class UngzipHandler implements Runnable {

    static org.apache.log4j.Logger logger = null;

    static {
        logger = org.apache.log4j.Logger.getLogger(UngzipHandler.class.getName());
    }
    ThreadPoolExecutor threadpool;

    public UngzipHandler() {
        threadpool = new ThreadPoolExecutor(12, 12, 3, TimeUnit.SECONDS,
                new LinkedBlockingQueue<Runnable>(100),
                new ThreadFactory() {
            AtomicInteger idx = new AtomicInteger(0);

            @Override
            public Thread newThread(Runnable r) {
                return new Thread(r, "JsonUnzipTask_" + idx.getAndIncrement());
            }
        }, new RejectedExecutionHandler() {

            @Override
            public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                while (true) {
                    try {
                        executor.getQueue().put(r);
                        break;
                    } catch (InterruptedException ex) {
                        logger.warn("", ex);
                    }
                }
            }
        });
    }

    @Override
    public void run() {
        logger.info("The uncompress gzFile is running!");
        ArrayList<String> fileList = new ArrayList<String>(50);
        while (true) {
            try {
                String str = GlobalParas.ungzipQueue.poll(500, TimeUnit.MILLISECONDS);
//				if (str == null) {
//					break;
//				}
                if (str == null || str.isEmpty() || str == "") {
                    Thread.sleep(5000);
                } else if (!str.isEmpty() && str != null && str != "") {
                    threadpool.execute(new UngzipTask(str));
                }
            } catch (Exception ex) {
                logger.error("this unzip  threadpool error :" + ex, ex);

            }
        }
    }

}
